﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
////////using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using QuanLyKho.Common;
using System.Net;

using System.IO;
using QuanLyKho.GUI.Library;
using System.Collections.Specialized;
using System.Xml;
using QuanLyKho.DataAccess;
using System.Security;
using System.Threading;
using Microsoft.SqlServer.Management.Smo;


namespace QuanLyKho.GUI
{
    public partial class frmConnect : Form
    {
        private static bool flag_authencation = false;
        public static string connString = string.Empty; //Chuoi ket noi
        static public string tenmaychu = string.Empty; //Ten may chu

        private BackgroundWorker bgWork;
        public BackgroundWorker BgWork
        {
            get { return bgWork; }
            set { bgWork = value; }
        }

        private const string findDbName = "QuanLyKho"; //Ten Database mac dinh khi phat trien
        static public string dbName = "";
        private string filename = "", urlMDF = "", urlLDF = "";
        static public string duongdan = @"C:\Database\";
        private clsDbTool objDbTool = null;
        private StringCollection strColl;

        private string type = "MainIsNotTrue";

        public frmConnect()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            try
            {
                rbtChonTaiKhoan.SelectedIndex = 0;
                ShowServerName();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// Hien thi ten may chu
        /// </summary>
        public void ShowServerName()
        {
            try
            {
                string ServerName = new clsDbTool().getServerName();
                txtTenMayChu.Text = ServerName.TrimEnd(';');
            }
            catch (Exception ex)
            {
                HavitelMessageBox.Show("Có lỗi ngẫu nhiên xảy ra, liên quan đến Sqlpress32.exe, để đảm bảo hệ thống hoạt động ổn định, hãy cài lại nó!","Thông báo", HavitelMessageBox.HavitelMessageButton.OK, HavitelMessageBox.HavitelMessageIcon.Warning);
            }
            //string hostname = Dns.GetHostName();
        }
        /// <summary>
        /// Thiet lap an hien cac button control.
        /// 
        /// Thiet lap dbName = ten findDbName mac dinh da duoc khoi tao.
        /// </summary>
        public void ShowSelectCSDL()
        {
            dbName = new clsDbTool(tenmaychu).getDbName(findDbName); //Lay ten database
            if (!string.IsNullOrEmpty(dbName))
            {
                txtCSDL.Text = dbName;
                btnKetNoi.Enabled = true;
                btnDelete.Enabled = true;
                btnRestore.Enabled = true;
                btnDetach.Enabled = true;
                btnAttach.Enabled = false;
            }
            else
            {
                txtCSDL.Text = "";
                dbName = findDbName;
                btnKetNoi.Enabled = false;
                btnRestore.Enabled = true;
                btnAttach.Enabled = true;
                btnDelete.Enabled = false;
                btnDetach.Enabled = false;
            }
            
        }

        /// <summary>
        /// Dinh dang chuoi xml dung de ket noi
        /// </summary>
        /// <returns></returns>
        private string xmlConnect()
        {
            string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine;
            xml += "<Connectionstring>" + Environment.NewLine;
            xml += "<List>" + Environment.NewLine;
            xml += "<Description>" + SecurityElement.Escape("PHẦN MỀM QUẢN LÝ KHO VẬT TƯ") + "</Description>" + Environment.NewLine;
            xml += "<ServerName>" + txtTenMayChu.Text + "</ServerName>" + Environment.NewLine;
            xml += "<DbName>" + txtCSDL.Text + "</DbName>" + Environment.NewLine;
            xml += "<UserId>" + txtTaiKhoan.Text + "</UserId>" + Environment.NewLine;
            xml += "<Password>" + txtMatKhau.Text + "</Password>" + Environment.NewLine;
            if (flag_authencation)
                xml += "<ConnectType>window Authenticate</ConnectType>";
            else
                xml += "<ConnectType>Sql Server Authenticate</ConnectType>";
            xml += "</List>" + Environment.NewLine;
            xml += "</Connectionstring>" + Environment.NewLine;

            return xml;
        }
        /// <summary>
        /// Kiem tra ten may chu va quyen truy cap Database
        /// </summary>
        private void f_connect()
        {
            if (!flag_authencation)
            {
                if (txtTaiKhoan.Text.Equals(""))
                {
                    lblTitile.Text = "Hãy nhập tài khoản để truy cập server";
                    txtTaiKhoan.Focus();
                    return;
                }
                else if (txtMatKhau.Text.Equals(""))
                {
                    lblTitile.Text = "Hãy nhập mật khẩu để truy cập Server";
                    txtMatKhau.Focus();
                    return;
                }
            }
            
            tenmaychu = txtTenMayChu.Text;
            ShowSelectCSDL();
        }
        /// <summary>
        /// Kiem tra ket noi toi Databse
        /// </summary>

        private void btnKetNoi_Click(object sender, EventArgs e)
        {
            type = "Connect";
            BgWork = new BackgroundWorker();
            BgWork.RunWorkerAsync();
            BgWork.DoWork += new DoWorkEventHandler(BgWork_DoWork);
            BgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWork_RunWorkerCompleted);
            pictureBox1.Visible = true;
            lblTitile.Location = new Point(37, lblTitile.Location.Y);
            pnLoading.Visible = true;
        }

        private void btnAttach_Click(object sender, EventArgs e)
        {
            filename = new clsLibrary().SelectTextFile(@"C:\", true);
            if (!string.IsNullOrEmpty(filename))
            {
                strColl = new StringCollection();
                strColl.Add(filename);

                type = "Attach";
                BgWork = new BackgroundWorker();
                BgWork.RunWorkerAsync();
                BgWork.DoWork += new DoWorkEventHandler(BgWork_DoWork);
                BgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWork_RunWorkerCompleted);
                pictureBox1.Visible = true;
                lblTitile.Location = new Point(37, lblTitile.Location.Y);
                pnLoading.Visible = true;
            }
        }

        private void btnDetach_Click(object sender, EventArgs e)
        {
            type = "Detach";
            BgWork = new BackgroundWorker();
            BgWork.RunWorkerAsync();
            BgWork.DoWork += new DoWorkEventHandler(BgWork_DoWork);
            BgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWork_RunWorkerCompleted);
            pictureBox1.Visible = true;
            lblTitile.Location = new Point(37, lblTitile.Location.Y);
            pnLoading.Visible = true;
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            type = "Restore";
            objDbTool = new clsDbTool(txtTenMayChu.Text);
            if (dbName.Length > 0)
                objDbTool.KillAllProcess(dbName);

            filename = new clsLibrary().SelectTextFile(@"C:\", false);
            if (!string.IsNullOrEmpty(filename))
            {
                if (!Directory.Exists(duongdan))
                {
                    DirectoryInfo di = new DirectoryInfo(duongdan);
                    di.Create();
                    di.Attributes = FileAttributes.System;
                }
                urlMDF = duongdan + dbName + ".mdf";
                urlLDF = duongdan + dbName + "_log.ldf";

                BgWork = new BackgroundWorker();
                BgWork.RunWorkerAsync();
                BgWork.DoWork += new DoWorkEventHandler(BgWork_DoWork);
                BgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWork_RunWorkerCompleted);
                pictureBox1.Visible = true;
                lblTitile.Location = new Point(37, lblTitile.Location.Y);
                pnLoading.Visible = true;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            type = "Delete";
            BgWork = new BackgroundWorker();
            BgWork.RunWorkerAsync();
            BgWork.DoWork += new DoWorkEventHandler(BgWork_DoWork);
            BgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWork_RunWorkerCompleted);
            pictureBox1.Visible = true;
            lblTitile.Location = new Point(37, lblTitile.Location.Y);
            pnLoading.Visible = true;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void rbtChonTaiKhoan_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbtChonTaiKhoan.SelectedIndex == 0)
            {
                flag_authencation = true;
                txtTaiKhoan.Enabled = false;
                txtMatKhau.Enabled = false;
                txtTaiKhoan.Text = "";
                txtMatKhau.Text = "";
            }
            else
            {
                flag_authencation = false;
                txtTaiKhoan.Enabled = true;
                txtMatKhau.Enabled = true;
            }
        }

        [STAThread]
        void BgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lblTitile.Location = new Point(pictureBox1.Location.X, lblTitile.Location.Y);
            pictureBox1.Visible = false;
            BgWork.Dispose();
        }

        [STAThread]
        void BgWork_DoWork(object sender, DoWorkEventArgs e)
        {
            #region ATTACH DATABASE
            if (type == "Attach")
            {
                try
                {
                    lblTitile.Text = "Đang attach database...";
                    objDbTool = new clsDbTool(tenmaychu);
                    objDbTool.AttachDatabase(dbName, strColl, AttachOptions.None);
                    lblTitile.Text = "Attach Database thành công.";
                    f_connect();
                }
                catch (Exception ex)
                {
                    lblTitile.Text = "Có lỗi xảy ra trong quá trình Attach CSDL";
                }
            }
            #endregion

            #region DETACH DATABASE
            if (type == "Detach")
            {
                try
                {
                    objDbTool = new clsDbTool(tenmaychu);
                    objDbTool.KillAllProcess(dbName);
                    lblTitile.Text = "Đang detach database...";
                    if (!string.IsNullOrEmpty(txtCSDL.Text))
                    {
                        objDbTool.DetachDatabase(txtCSDL.Text, true, true);
                        lblTitile.Text = "Detach Database thành công.";
                        f_connect();
                    }
                }
                catch (Exception ex)
                {
                    lblTitile.Text = "Có lỗi xảy ra trong quá trình Detach CSDL.";
                }
            }
            #endregion

            #region DELETE DATABASE
            if (type == "Delete")
            {
                try
                {
                    lblTitile.Text = "Đang xóa database...";
                    objDbTool = new clsDbTool(tenmaychu);
                    objDbTool.KillAllProcess(dbName);

                    objDbTool.DeleteDatabase(dbName);
                    lblTitile.Text = "Xóa database thành công";
                    f_connect();
                }
                catch (Exception ex)
                {
                    HavitelMessageBox.Show("Có lỗi xảy ra trong quá trình xóa database : \r\n" + ex.ToString(), "Thông báo", HavitelMessageBox.HavitelMessageButton.OK, HavitelMessageBox.HavitelMessageIcon.Warning);
                }
            }
            #endregion

            #region RESTORE DATABASE
            if (type == "Restore")
            {
                try
                {
                    lblTitile.Text = "Đang restore database...";
                    objDbTool.RestoreDatabase(dbName, filename, dbName, dbName + "_log", urlMDF, urlLDF);
                    lblTitile.Text = "Restore Database thành công";
                    f_connect();   
                }
                catch (Exception ex)
                {
                    lblTitile.Text = "Có lỗi xảy ra trong quá trình Restore database.";
                }
            }
            #endregion

            #region CONNECT
            if (type == "Connect")
            {
                if (string.IsNullOrEmpty(txtCSDL.Text))
                {
                    lblTitile.Text = "Không có CSDL trong hệ thống.";
                    txtCSDL.Focus();
                    return;
                }
                lblTitile.Text = "Đang tạo file kết nối...";
                if (!Directory.Exists(new clsConnect().UrlFolder))
                {
                    DirectoryInfo di = new DirectoryInfo(new clsConnect().UrlFolder);
                    di.Create();
                    di.Attributes = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReadOnly;
                }

                FileInfo fi = new FileInfo(new clsConnect().UrlFile);
                if (!File.Exists(new clsConnect().UrlFile))
                {
                    FileStream fs = new FileStream(new clsConnect().UrlFile, FileMode.Create, FileAccess.ReadWrite);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(xmlConnect());
                    sw.Flush();
                    fs.Close();

                    fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System;
                }
                else
                {
                    fi.Attributes = FileAttributes.Normal;
                    fi.Delete();
                    FileStream fs = new FileStream(new clsConnect().UrlFile, FileMode.Create, FileAccess.ReadWrite);
                    StreamWriter sw = new StreamWriter(fs);
                    sw.Write(xmlConnect());
                    sw.Flush();
                    fs.Close();

                    fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System;
                }

                lblTitile.Text = "Đã tạo thành công file kết nối...Truy cập hệ thống sau 3 giây.";
                Thread.Sleep(3000);
                //this.WindowState = FormWindowState.Minimized;

                Thread thread = new Thread(new ThreadStart(new clsLibrary().runLogin));
                thread.Name = "Login";
                thread.ApartmentState = ApartmentState.STA;
                thread.Start();
                this.Close();

            }
            #endregion

            #region CHECK CONNECT
            if (type == "CheckConnect")
            {
                try
                {
                    lblTitile.Text = "Đang kiểm tra kết nối...";
                    f_connect();
                    if (!string.IsNullOrEmpty(dbName))
                    {
                        lblTitile.Text = "Kết nối Server thành công.";
                        btnCheckConnect.Text = "Kết nối CSDL thành công!.\n\n Kết nối lại?";
                    }
                    else
                    {
                        lblTitile.Text = "Không có kết nối tới Server.";
                        btnCheckConnect.Text = "Kiểm tra kết nối.";
                    }
                }
                catch (Exception ex)
                {
                    lblTitile.Text = "Không có kết nối tới Server.";
                }
            }
            #endregion
        }

        private void btnCheckConnect_Click(object sender, EventArgs e)
        {
            type = "CheckConnect";
            btnCheckConnect.Text = "Đang kiểm tra kết nối...";
            BgWork = new BackgroundWorker();
            BgWork.RunWorkerAsync();
            BgWork.DoWork += new DoWorkEventHandler(BgWork_DoWork);
            BgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BgWork_RunWorkerCompleted);
            pictureBox1.Visible = true;
            lblTitile.Location = new Point(37, lblTitile.Location.Y);
            pnLoading.Visible = true;
        }

        
    }
}
